// 权限控制

import router from '@/router'
import store from '@/store'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import permissionRoute from '@/router/modules/permission'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  NProgress.start()
  const { userInfo, power } = store.state.user
  if (userInfo.uname) {
    if (!power) {
      await store.dispatch('user/getPower', userInfo.power)
      if (userInfo.power && userInfo.power.includes('管理员')) {
        router.addRoutes([permissionRoute, { path: '*', redirect: '/404', hidden: true }])
        store.commit('user/setRoutes', [permissionRoute])
      } else {
        router.addRoutes([{ path: '*', redirect: '/404', hidden: true }])
      }
      next({ ...to, replace: true })
    }
    if (to.path === '/login') {
      next('/')
      NProgress.done()
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      store.commit('user/removeUserInfo')
      next('/login')
      NProgress.done()
    }
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})
